import threading
import time


class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self):
        super(StoppableThread, self).__init__()
        self._stop_event = threading.Event()

    def stop(self):
        self._stop_event.set()

    @property
    def stopped(self):
        return self._stop_event.is_set()


class MyThread(StoppableThread):

    def __init__(self, i):
        super(MyThread, self).__init__()
        self.i = i

    def run(self):
        while True:
            print(self.i)
            time.sleep(2)
            if self.stopped:
                print('%d exit...' % self.i)
                break

def main():
    threads = []
    for i in range(10):
        thread = MyThread(i)
        # thread.setDaemon(True) # 守护进程系统不管
        thread.start()
        threads.append(thread)
    try:
        for thread in threads:
            thread.join()
    except KeyboardInterrupt:
        print('Please wait for threads to exit gracefully!')
        for thread in threads:
            thread.stop()
        for thread in threads:
            thread.join()

if __name__ == '__main__':
    main()
